# coding: utf-8
import pyperclip
from urllib.request import urlretrieve
from qiniu import Auth, put_file, etag
import time, os

def download():
    # 获取你想下载的图片链接
    img_url = input("输入图片外链：")
    # 获取当前时间戳作为文件名
    img_filename = str(int(time.time()))
    # 拼接路径
    img_path = "./" + str(int(time.time())) + ".png"
    # 下载图片
    urlretrieve(img_url, img_path)
    return img_filename, img_path

def upload(img_filename, img_path):
    # 上传到七牛云
    # __access_key: 账号密钥对中的accessKey，详见 https://portal.qiniu.com/user/key
    # __secret_key: 账号密钥对重的secretKey，详见 https://portal.qiniu.com/user/key
    access_key = "你的__access_key"
    secret_key = "你的__secret_key"

    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = '你的空间名'
    # 上传后保存的文件名
    key = img_filename + '.png'
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)

    ret, info = put_file(token, key, img_path)
    assert ret['key'] == key
    assert ret['hash'] == etag(img_path)

    # 七牛云的域名
    place = "example.xucooler.top"
    if info.status_code == 200:
        site = "http://" + place + "/" + img_filename + '.png'
        print("生成链接：" + site)
        # 将链接复制到粘贴板
        pyperclip.copy(site)
        print("上传成功，图片链接已复制到粘贴板")
        # 删除下载的图片文件
        os.remove(key)
    else:
        print("上传失败，错误如下")
        print(info)

if __name__ == '__main__':
    flag = 1
    while(flag != '0'):
        img_filename, img_path = download()
        upload(img_filename, img_path)
        flag = input("输0退出，若想继续请直接按回车键:")